package com.musicstore.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.musicstore.dao.MyBatisUtil;
import com.musicstore.dao.UserDao;
import com.musicstore.entity.User;

/**
 * Servlet implementation class AddUser
 */
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		User user =new User();
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("userpwd"));
		user.setAddress(request.getParameter("add"));
		user.setPhone(request.getParameter("phon"));
		user.setEmail(request.getParameter("email"));
		user.setInUse(true);
		SqlSession session =MyBatisUtil.openSession();
		UserDao userDao =session.getMapper(UserDao.class);
		boolean bool=true;
		try {
			userDao.register(user);
			session.commit();
		} catch (Exception e) {
			bool=false;
			session.rollback();
		}
		if(bool){
			request.setAttribute("message", user.getName());
			request.getRequestDispatcher("show.jsp").forward(request, response);
		}else {
			request.setAttribute("message", "注册失败");
			request.getRequestDispatcher("enroll.jsp").forward(request, response);
		}
	}

}
